package com.xzx.study.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import com.xzx.study.R;

// 动态加载
public class FragmentDemo2Activity extends FragmentActivity implements View.OnClickListener {

    private Button btn_add_fragment;
    private Button btn_remove_fragment;
    private LinearLayout fragment_container;

    private Fragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_demo2);

        btn_add_fragment = findViewById(R.id.btn_add_fragment);
        btn_remove_fragment = findViewById(R.id.btn_remove_fragment);
        fragment_container = findViewById(R.id.fragment_container);

        Fragment fragment = new Fragment1();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fragment_container, fragment).commit();

        btn_add_fragment.setOnClickListener(this);
        btn_remove_fragment.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == btn_add_fragment) {
            fragment = new Fragment2();
            getSupportFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.fragment_container,
                                                                                     fragment).commit();
        } else if (v == btn_remove_fragment) {
            getSupportFragmentManager().beginTransaction().remove(fragment).commit();
        }
    }
}
